package com.recipedb.recipedb.service.impl;

import com.recipedb.recipedb.entity.UserMessage;
import com.recipedb.recipedb.repository.UserMessageRepository;
import com.recipedb.recipedb.service.UserMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;

@Service
public class UserMessageServiceImpl implements UserMessageService {

    @Autowired
    private UserMessageRepository repository;

    @Override
    public UserMessage save(UserMessage entity) {
        return repository.save(entity);
    }

    @Override
    public void deleteById(Long id) {
        repository.deleteById(id);
    }

    @Override
    public Optional<UserMessage> findById(Long id) {
        return repository.findById(id);
    }

    @Override
    public List<UserMessage> findAll() {
        return repository.findAll();
    }

    @Override
    public List<UserMessage> findByUserId(Long userId) {
        return repository.findByUserIdOrderByCreatedAtDesc(userId);
    }

    @Override
    public List<UserMessage> findUnreadByUserId(Long userId) {
        return repository.findByUserIdAndReadFlagFalseOrderByCreatedAtDesc(userId);
    }

    @Override
    public void markAllAsRead(Long userId) {
        List<UserMessage> unreadMessages = repository.findByUserIdAndReadFlagFalse(userId);
        for (UserMessage message : unreadMessages) {
            message.setReadFlag(true);
        }
        repository.saveAll(unreadMessages);
    }
}
